package com.heima.wemedia.inteceptor;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.util.WmThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WmTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求是否来自网关，如果不是直接抛异常
        String requestHeader = request.getHeader("X-Request-From");
        if (!StrUtil.equals(requestHeader, "heima-leadnews-wemedia-gateway")){
            response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
            return false;
        }

        // 获取请求头中的userId，将其封装到ThreadLocal中
        String userId = request.getHeader("userId");
        if (StrUtil.isNotEmpty(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Convert.toInt(userId));
            WmThreadLocal.setUser(wmUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocal.clear();
    }
}
